package com.hk.Mgr.web.controller.kyc;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.kyc.AgreementReq;
import com.hk.Mgr.web.message.kyc.AgreementRes;
import com.hk.Mgr.web.message.sys.SysUserReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.entity.Agreement;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.kyc.IAgreement;
import com.hk.service.sys.ISysUser;

@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/agreementCtrl")
public class AgreementCtrl extends BaseCtrl {

	@Autowired
	private IAgreement agreementService;

	@Autowired
	private ISysUser sysUserService;

	private Logger logger = LoggerFactory.getLogger(AgreementCtrl.class);

	@Autowired
	public YingmiApiUtils utils;

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> updateAgreement(@RequestBody AgreementReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Agreement ag = new Agreement();

		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				resp.setResult(true);
				resp.setResultCode(StatusCode.ERROR.key());
				return resp;
			} else {
				ReqToModelHelper.copyReqValueToModel(req, ag);

				if (StringUtils.isNotBlank(req.getAgreement())) {
					byte[] agreement = req.getAgreement().getBytes("UTF-8");
					ag.setAgreement(agreement);
				}

				agreementService.update(ag);
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
			}

		} catch (Exception e) {
			logger.error("保存协议失败");
			resp.setMsg("保存协议失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 获得所有订单信息
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<AgreementRes>> list(@RequestBody SysUserReq req) {
		ResponseBase<List<AgreementRes>> resp = new ResponseBase<>();
		List<AgreementRes> orderReslist = new ArrayList<>();

		HqlFilter hqlFilter = new HqlFilter();

		if (StringUtils.isNotEmpty(req.getName())) {
			hqlFilter.addLKFilter("name", req.getName());
		}

		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");

		List<Agreement> list = agreementService.findByFilter(hqlFilter,
				req.getCurPage(), req.getPageSize());

		for (Agreement ag : list) {
			AgreementRes agreementRes = new AgreementRes();

			ReqToModelHelper.copyReqValueToModel(ag, agreementRes);

			// 增添创建者姓名
			SysUser creater = new SysUser();
			if (ag.getCreater() != null
					&& sysUserService.existById(ag.getCreater())) {
				creater = sysUserService.findById(ag.getCreater());
				agreementRes.setCreaterName(creater.getRealName());
			}

			if (ag.getAgreement() != null) {
				String agreement;
				try {
					agreement = new String(ag.getAgreement(), "UTF-8");
					agreementRes.setAgreementText(agreement);

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error("agreementCtl/update 类型转换错误" + "id = "
							+ req.getId());
				}

				orderReslist.add(agreementRes);
			}
			resp.setResult(orderReslist);
			resp.setSize(orderReslist.size());
			resp.setResult(orderReslist);
		}

		return resp;
	}

	/**
	 * 获得所有订单信息
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/getById", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<AgreementRes> getById(String id) {
		ResponseBase<AgreementRes> resp = new ResponseBase<>();
		
		Long idLong = Long.valueOf(id);

		if (idLong == null) {
			resp.setMsg("协议不存在，请重试");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		Agreement agreement = agreementService.findById(idLong);

		if (agreement == null) {
			resp.setMsg("协议不存在，请重试");
			resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
			return resp;
		}

		AgreementRes agreementRes = new AgreementRes();

		ReqToModelHelper.copyReqValueToModel(agreement, agreementRes);

		String agreementContext;
		try {
			agreementContext = new String(agreement.getAgreement(), "UTF-8");
			agreementRes.setAgreementText(agreementContext);
			resp.setResult(agreementRes);
			resp.setResultCode(StatusCode.SUCCESS.key());

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.error("agreementCtl/update 类型转换错误" + "id = " + id);
			
			resp.setMsg("协议内容转换错误，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> save(@RequestBody AgreementReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Agreement ag = new Agreement();

		try {
			ReqToModelHelper.copyReqValueToModel(req, ag);
			Long id = null;
			if (StringUtils.isNotBlank(req.getAgreement())) {
				byte[] agreement = req.getAgreement().getBytes("UTF-8");
				ag.setAgreement(agreement);
			}

			id = agreementService.add(ag);
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());

		} catch (Exception e) {
			logger.error("保存协议失败");
			resp.setMsg("保存协议失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
}
